// @login & register的路由
//fixme 虽然主文件app.js已经引入了express  但是路由模块还是需要再引入express
const express = require('express');
const router = express.Router();
const UserModel = require('../../models/User')
//todo body-parser的作用：解析post请求，使req.body.xxx能够拿到请求参数
const bodyParser = require('body-parser');
//TODO 密码加密bcrypt
const bcrypt = require('bcrypt');
//TODO 头像全球通用模块 https://www.npmjs.com/package/gravatar
const gravatar = require('gravatar');
//fixme 用于鉴权 https://www.npmjs.com/package/jsonwebtoken
const jwt = require('jsonwebtoken');
const keys=require('../../config/keys')

// @route  GET api/users/test
// @desc   返回的请求的json数据
// @access public
router.get('/', (req, res) => {
    res.json({msg: 'hahahahha'})

});
// @route  POST api/users/register
// @desc   返回的请求的json数据
// @access public
router.post('/register',  (req,res)=>{
// 查询数据库中是否拥有邮箱
    //fixme 这里他用的是promise的写法 也可以参考硅谷直聘的写法
    // TODO UserModel.findOne({username}, function (err, user) {
    UserModel.findOne({email:req.body.email}).then((user)=>{
        if(user) {
            return res.status(400).json('邮箱已被注册！')
        }else{
            //fixme 使用第三方模块gravatar全球通用头像 https://www.npmjs.com/package/gravatar
            /*options: Query string options. Ex: size or s, default or d, rating or r, forcedefault or f.
            Additional options not passed as a query string: protocol (e.g. "http" or "https") and
            format (only for profile_url, e.g. "xml", "qr", by default it is "json")
            Should be passed as an object. Ex: {s: '200', f: 'y', d: '404'}*/
            const avatar = gravatar.url(req.body.email, {
                s: '200',
                r: 'pg',
                d: 'mm'
            });
            //新建用户对象
            const newUser = new User({
                name: req.body.name,
                email: req.body.email,
                avatar,
                password: req.body.password,
                identity: req.body.identity
            })
            //fixme bcrypt加密 参考https://www.npmjs.com/package/bcrypt
            /*
            bcrypt.genSalt(saltRounds, function(err, salt) {
                bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
                    // Store hash in your password DB.
                });
            });*/
            bcrypt.genSalt(10,function(err, salt) {
                //todo newUser.password要加密的密码    hash是加密成功后的密码
                bcrypt.hash(newUser.password, salt, (err, hash) => {
                    if(err) throw err;
                    //todo hash是加密后的密码赋值给密码
                    newUser.password = hash;
                    newUser.save()
                        .then(user => res.json(user))
                        .catch(err => console.log(err));
                })
            })
        }
    })
})

//登录功能
// @route  POST api/users/login
// @desc   返回token jwt passport
// @access public
router.post('/login',(req,res)=>{
    const email = req.body.email;
    const password = req.body.password;

    // 查询数据库
    UserModel.findOne({email:email},function (err, data) {
        if(!data) {
            res.status(404).json('用户不存在')
        }
        // fixme bcrypt.compare密码匹配 password:前端传的密码
        bcrypt.compare(password,data.password).then((isMatch)=>{
            if(isMatch) {
                //fixme jwt的payload：承装的信息
                const rule = {
                    id: data.id,
                    name: data.name,
                    avatar: data.avatar,
                    identity: data.identity
                }
                //fixme jsonwebtoken用法：https://www.npmjs.com/package/jsonwebtoken
                //fixme jwt.sign(payload信息，秘钥名字，expiresIn过期时间（秒），箭头函数)
                /*jwt.sign(payload, secretOrPrivateKey, [options, callback])
                * */
                jwt.sign(rule,keys.secretOrKey,{ expiresIn: 3600 },(err, token)=>{
                    if (err) throw err;
                    res.json({
                        success: true,
                        //fixme 返回给浏览器的token 要带着'Bearer ' 前缀 有空格  下次访问时Authorization:token
                        //todo 下次前端请求时会用axios拦截器 给请求头加上token
                        token: 'Bearer ' + token
                    })
                })
            }else {
                //密码对比匹配失败
                return res.status(400).json('密码错误!!!!!!!!!!!!');
            }
        })
    })

})


/*TODO 报错就是找不到这个模块，原因：重命名的文件他找不到，必须删了重新写*/
module.exports =router